package sopia.sg;

import java.util.ArrayList;


import sopia.cmm.CommonFunct;
import sopia.conn.CustomerSpinnerAdapter;
import sopia.conn.ItemExpenseAdapter;
import sopia.ctrl.ItemExpense;
import sopia.ctrl.ItemExpenseCustomizeAdapter;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources.NotFoundException;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;



public class G008Activity extends ListActivity {
	private ItemExpenseAdapter itemExpAdapter ;
	private ListView listItem;
	private ItemExpenseCustomizeAdapter itemExpenseCustomizeAdapter;
	private ItemExpenseCustomizeAdapter itemExpenseCustomizeAdapterFilter;
	private String screenID;
	private EditText filterEditText;
	private ArrayList<ItemExpense> arrItemExp;
	@Override
	public void onCreate(Bundle savedInstanceState) {
	  super.onCreate(savedInstanceState);
	  setContentView(R.layout.g008_layout);
	  
	  listItem = (ListView) findViewById(android.R.id.list);
	  arrItemExp = this.getListItemExpense();
	  itemExpenseCustomizeAdapter = new ItemExpenseCustomizeAdapter(this, R.layout.item_customer_layout,
			  arrItemExp);
	  listItem.setAdapter(itemExpenseCustomizeAdapter);
	  registerForContextMenu(listItem);
	 // listItem.setTextFilterEnabled(true);
//	  listItem.
//	  setListAdapter(new ArrayAdapter<ItemExpense>(this, R.layout.g008_layout, 
//			  this.getListItemExpense()));
//
//	  ListView lv = getListView();
//	  lv.setTextFilterEnabled(true);

//	  lv.setOnItemClickListener(new OnItemClickListener() {
//	    public void onItemClick(AdapterView<?> parent, View view,
//	        int position, long id) {
//	      // When clicked, show a toast with the TextView text
//	      Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
//	          Toast.LENGTH_SHORT).show();
//	    }
//	  });
	  //back menu
	  Intent receiveIntent = this.getIntent();
	  this.screenID = receiveIntent.getStringExtra("ID");
	  //filter
	  filterEditText = (EditText) findViewById(R.id.filterEdit);
      filterEditText.addTextChangedListener(new TextWatcher() {

          @Override
          public void onTextChanged(CharSequence s, int start, int before,
                  int count) {
        	  //itemExpenseCustomizeAdapter.getFilter().filter(s.toString());
        	  filterAdapter(s.toString());        	 
        	  
          }

          @Override
          public void beforeTextChanged(CharSequence s, int start, int count,
                  int after) {
          }

          @Override
          public void afterTextChanged(Editable s) {
        	  
          }
      });

	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	  //Handle the back button
	  if (keyCode == KeyEvent.KEYCODE_BACK) {
			backToPreviousScreen();
	    return true;
	  }
	  return super.onKeyDown(keyCode, event);
	} 
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
        ContextMenuInfo menuInfo) {
	      try {
			if (v.getId()== android.R.id.list) {
			    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
			    ItemExpenseCustomizeAdapter itemExpenseCustomizeAdapter =  (ItemExpenseCustomizeAdapter) listItem.getAdapter();
			    ArrayList<ItemExpense> arrayItem = itemExpenseCustomizeAdapter.array;
			    menu.setHeaderTitle(arrayItem.get(info.position).getItem());
			    String[] menuItems = getResources().getStringArray(R.array.menu);
			    for (int i = 0; i<menuItems.length; i++) {
			      menu.add(Menu.NONE, i, i, menuItems[i]);
			    }
			  }
		} catch (NotFoundException e) {
			e.printStackTrace();
		}
    }
    @Override
    public boolean onContextItemSelected(MenuItem item) {
      AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
      ItemExpenseCustomizeAdapter itemExpenseCustomizeAdapter =  (ItemExpenseCustomizeAdapter) listItem.getAdapter();
	  ArrayList<ItemExpense> arrayItem = itemExpenseCustomizeAdapter.array;	    
	  final ItemExpense itemExpense = arrayItem.get(info.position);
	  
      int menuItemIndex = item.getItemId();
//      String[] menuItems = getResources().getStringArray(R.array.menu);
//      String menuItemName = menuItems[menuItemIndex];
	 
      switch( menuItemIndex)
      {
	      case 0: //delete	    
	    	  	new AlertDialog.Builder(this)
	    	    .setTitle(CommonFunct.join("Delete item ", itemExpense.getItem()))
	    	    .setMessage("Are you sure you want to delete this item?")
	    	    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
	    	        public void onClick(DialogInterface dialog, int which) { 
	    	            deleteItemExpense(itemExpense);
	    	        }
	    	     })
	    	    .setNegativeButton("No", new DialogInterface.OnClickListener() {
	    	        public void onClick(DialogInterface dialog, int which) { 
	    	            // do nothing
	    	        }
	    	     })
	    	     .show();	    	  
	    	  break;
	      case 1: // show details
	    	  
	    	  break;
	      default:
	    	  
      }
    

      return true;
    }
	protected void deleteItemExpense(ItemExpense itemExpense) {
		try {
			itemExpAdapter = new ItemExpenseAdapter(this);
			if(itemExpAdapter.deleteItemExpense(itemExpense)){
				itemExpAdapter.close();
				Toast.makeText(this,"Removed item selected." , Toast.LENGTH_LONG).show();
				arrItemExp = this.getListItemExpense();
			    itemExpenseCustomizeAdapter = new ItemExpenseCustomizeAdapter(this, R.layout.item_customer_layout,
					  arrItemExp);
				listItem.setAdapter(itemExpenseCustomizeAdapter);
				filterAdapter(filterEditText.getText().toString());     
				 
			}	
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	protected void filterAdapter(String filter) {
		if(arrItemExp.size() > 0){
			ArrayList<ItemExpense> arrItemExpFilter = new ArrayList<ItemExpense>();
			ItemExpense item;
			for(int i = 0 ;i < arrItemExp.size() ; i++){
				item = arrItemExp.get(i);
				if(item.getItem().toLowerCase().contains(filter) 
						|| item.getAccount().toLowerCase().contains(filter)
						|| item.getType().toLowerCase().contains(filter)
						|| item.getComment().toLowerCase().contains(filter)
						|| item.getDate().toLowerCase().contains(filter)
						|| item.getAmount().toLowerCase().contains(filter)){
					arrItemExpFilter.add(item);
				}
			}
			if(arrItemExpFilter.size() > 0) {
				itemExpenseCustomizeAdapterFilter = new ItemExpenseCustomizeAdapter(this, R.layout.item_customer_layout,
						arrItemExpFilter);
				listItem.setAdapter(itemExpenseCustomizeAdapterFilter);
			}else{
				itemExpenseCustomizeAdapter.getFilter().filter(filter);
				listItem.setAdapter(itemExpenseCustomizeAdapter);
			}
		}	
		 
	}
	protected void backToPreviousScreen() {
		Intent i = null;
		if("G001".equals(this.screenID)){
			i = new Intent(G008Activity.this, G001Activity.class);
		}
		i.putExtra("ID", "G008");
		startActivity(i);
		finish();
	}
	private ArrayList<ItemExpense> getListItemExpense(){
		ArrayList<ItemExpense> arrReult = new ArrayList<ItemExpense>();
		try {
			itemExpAdapter = new ItemExpenseAdapter(this);
			Cursor cur = itemExpAdapter.getAllItemExpense();
			ItemExpense item ;
			if (cur.moveToFirst()) {
		         do {
		        	 item = new ItemExpense();
		        	 item.setAccount(cur.getString(5));
		        	 item.setItem(cur.getString(0));
		        	 item.setAmount(cur.getString(2));
		        	 item.setType(cur.getString(1));
		        	 item.setDate(cur.getString(3));
		        	 item.setComment(cur.getString(4));
		        	 arrReult.add(item);
		         } while (cur.moveToNext());
		      }
		      if (cur != null && !cur.isClosed()) {
		    	  cur.close();
		      }
			itemExpAdapter.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return arrReult;
	}

}
